﻿using ServiceMonitor.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ServiceMonitor.Services.Impl
{
    /// <summary>
    /// Http 健康检查服务实现类
    /// </summary>
    public class HttpHealthMonitorServiceImpl : AbstractStartMonitoringService
    {

        private readonly Action<String> _logger;
        private readonly MonitorConfig _config;
        private Action<string> logger;
        private Timer _monitoringTimer;
        private static Object lock_obj = new Object();
        public HttpHealthMonitorServiceImpl(
            EventHandler<ServiceStatusChangedEventArgs> eventHandler,
            MonitorConfig config,
            Action<string> logger) : base(eventHandler)
        {
            _config = config;
            this.logger = logger;
        }

        public override void Start(Object obj)
        {
            _monitoringTimer = new Timer(CheckServiceStatus, null, Timeout.Infinite, Timeout.Infinite);
            _monitoringTimer.Change(0, _config.CheckInterval * 1000);
        }

        public override void CheckServiceStatus(object state)
        {
            lock (lock_obj)
            {
                if (!MonitoringService.GetIsMonitoring())
                {
                    return;
                }
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_config.Url);
                    request.Timeout = _config.Timeout;
                    request.Method = "HEAD"; // 使用更轻量的HEAD请求

                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        int statusCode = (int)response.StatusCode;
                        if (statusCode == (int)_config.ExpectedStatus)
                        {
                            UpdateStatus(_config.Id, $"HTTP状态: {statusCode}");
                        }
                        else
                        {
                            throw new Exception($"预期状态码 {_config.ExpectedStatus}, 实际: {statusCode}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    UpdateStatus(_config.Id, $"HTTP检测失败: {ex.Message}");
                }
            }
        }
    }
}
